﻿Imports Microsoft.VisualBasic
Imports System.Text.RegularExpressions
Imports System.Collections.Generic
Imports System.Security.Cryptography
Imports System.Web.HttpContext

Public Class clsAuth
    Public Shared Function GetOrganizationName(ByVal UserID As String) As String
        Dim dat As New clsData
        Dim sql As New StringBuilder
        Dim dt As Data.DataTable  

        sql.AppendFormat("select b.OrganizationName ")
        sql.AppendFormat("from Employee a ")
        sql.AppendFormat("left join Organization b on a.OrganizationID=b.OrganizationID ")
        sql.AppendFormat("where a.EmployeeID = '{0}' ", UserID)

        dt = dat.GetData(sql) 

        If dt.Rows.Count > 0 Then
            Return dt.Rows(0)("OrganizationName")
        Else
            Return "-1"
        End If

    End Function
    ''' <summary>
    ''' 依登入者權限列出所有運用單位
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function GetDDLDirectOrganizationData() As Data.DataTable
        Dim dat As New clsData
        Dim sql As New MyStringBuilder
        Dim dt As Data.DataTable

        sql.Length = 0
        sql.AppendFormat("select ua.*, o.OrganizationName, UOrganizationID ")
        sql.AppendFormat("from UserOrganizationAuth ua ")
        sql.AppendFormat("inner join OrganizationView o on ua.OrganizationID = o.OrganizationID and ua.VOrganizationID = o.VOrganizationID ")
        sql.AppendFormat("where ua.UserID = '{0}' ", clsAuth.GetUserID())
        sql.AppendFormat("and o.OrganizationType in ('O','P') ")
        sql.AppendFormat("order by o.VOrganizationCode, o.OrganizationCode ")

        dt = dat.GetData(sql)

        Return dat.GetData(sql)
    End Function
    ''' <summary>
    ''' 重新計算組織權限 - depreciated
    ''' 組織權限目前由登入者所屬的組織來判斷
    ''' </summary>
    ''' <remarks></remarks>
    Public Shared Sub BuildRoleOrganizationMappingData()
        'Dim dat As New clsData
        'Dim sql As New StringBuilder

        'sql.Length = 0
        'sql.AppendFormat("select o.* ")
        'sql.AppendFormat("from Organization o ")
        'sql.AppendFormat("where o.Active = 'Y' ")

        'Dim dtOrganization As Data.DataTable = dat.GetData(sql.ToString(), Nothing, Data.CommandType.Text, "dt").Tables(0)

        'Using scope As New Transactions.TransactionScope
        '    sql.Length = 0
        '    sql.AppendFormat("select * into #RoleOrganizationMapping ")
        '    sql.AppendFormat("from RoleOrganizationMapping  ")

        '    dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)

        '    dtOrganization.DefaultView.RowFilter = String.Format("IsNull([Parent],-1) = -1 ")
        '    BuildRoleOrganizationMappingData_Process2(dtOrganization.DefaultView)

        '    sql.Length = 0
        '    sql.AppendFormat("truncate table ")
        '    sql.AppendFormat("RoleOrganizationMapping ")
        '    dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)

        '    sql.Length = 0
        '    sql.AppendFormat("insert RoleOrganizationMapping  (RoleID, OrganizationID, AuthName) ")
        '    sql.AppendFormat("select distinct RoleID, OrganizationID, AuthName ")
        '    sql.AppendFormat("from #RoleOrganizationMapping ")

        '    dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)

        '    sql.Length = 0
        '    sql.AppendFormat("drop table ")
        '    sql.AppendFormat("#RoleOrganizationMapping ")

        '    dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)

        '    scope.Complete()
        'End Using
    End Sub

    Private Shared Sub BuildRoleOrganizationMappingData_Process2(ByVal dvOrganization As Data.DataView)
        'If dvOrganization.Count = 0 Then
        '    Return
        'End If

        'Dim dat As New clsData
        'Dim sql As New StringBuilder

        'sql.Length = 0
        'sql.AppendFormat("insert #RoleOrganizationMapping (RoleID, OrganizationID, AuthName) select ")
        'sql.AppendFormat(" ro.RoleID, o.OrganizationID, ro.AuthName ")
        'sql.AppendFormat("from #RoleOrganizationMapping ro ")
        'sql.AppendFormat(", Organization o ")
        'sql.AppendFormat("where ro.OrganizationID = '{0}' ", dvOrganization(0)("Parent"))
        'sql.AppendFormat("and o.Parent = '{0}' ", dvOrganization(0)("Parent"))

        'dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)

        'For Each child As Data.DataRowView In dvOrganization
        '    Dim dv As Data.DataView = New Data.DataView(dvOrganization.Table)
        '    dv.RowFilter = String.Format("[Parent] = {0}", child("OrganizationID"))
        '    BuildRoleOrganizationMappingData_Process2(dv)
        'Next
    End Sub

    Public Shared Function GetProgramAuth(ByVal authName As String) As Boolean
        Dim url As String = HttpContext.Current.Request.RawUrl.Split("/")(HttpContext.Current.Request.RawUrl.Split("/").Length - 1)

        Return GetProgramAuth(url, authName)
    End Function

    Public Shared Function GetProgramAuth(ByVal url As String, ByVal authName As String) As Boolean
        Dim dat As New clsData
        Dim sql As New StringBuilder

        sql.Length = 0
        sql.AppendFormat("select rp.* ")
        sql.AppendFormat("from RoleProgramMappingView rp ")
        sql.AppendFormat("inner join ProtectedProgram p on rp.ProgramID = p.ProgramID ")
        sql.AppendFormat("where p.Url = '{0}' ", url)
        sql.AppendFormat("and (rp.AuthName = '{0}' or rp.AuthName = 'Admin') ", authName)
        sql.AppendFormat("and rp.RoleID in ({0}) ", GetRoleList())

        Return IIf(dat.GetData(sql.ToString(), Nothing, Data.CommandType.Text, "dt").Tables(0).Rows.Count = 0, False, True)

    End Function

    Public Shared Function GetProgramAuths(ByVal programName As String) As Data.DataTable
        Dim dat As New clsData
        Dim sql As New StringBuilder

        sql.Length = 0
        sql.AppendFormat("select pa.* ")
        sql.AppendFormat("from UserProgramAuth pa ")
        sql.AppendFormat("inner join ProtectedProgram p on pa.ProgramID = p.ProgramID ")
        sql.AppendFormat("where p.TableName = '{0}' ", programName)
        sql.AppendFormat("and pa.UserID = '{0}' ", GetUserID())

        Return dat.GetData(sql)
    End Function

    ''' <summary>
    ''' 以 table 名稱判斷權限, 常用於控制項, 因為控制項所屬的頁面是不確定的
    ''' </summary>
    ''' <param name="tableName"></param>
    ''' <param name="authName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function GetTableAuth(ByVal tableName As String, ByVal authName As String) As Boolean
        Dim dat As New clsData
        Dim sql As New StringBuilder

        sql.Length = 0
        sql.AppendFormat("select rp.* ")
        sql.AppendFormat("from RoleProgramMappingView rp ")
        sql.AppendFormat("inner join ProtectedProgram p on rp.ProgramID = p.ProgramID ")
        sql.AppendFormat("where p.TableName = '{0}' ", tableName)
        sql.AppendFormat("and (rp.AuthName = '{0}' or rp.AuthName = 'Admin') ", authName)
        sql.AppendFormat("and rp.RoleID in ({0}) ", GetRoleList())

        Return IIf(dat.GetData(sql.ToString(), Nothing, Data.CommandType.Text, "dt").Tables(0).Rows.Count = 0, False, True)

    End Function

    '''' <summary>
    '''' 以 table 名稱和單位判斷權限
    '''' </summary>
    '''' <param name="tableName"></param>
    '''' <param name="organizationID"></param>
    '''' <param name="authName"></param>
    '''' <returns></returns>
    '''' <remarks></remarks>
    'Public Shared Function GetTableAuth(ByVal tableName As String, ByVal organizationID As String, ByVal authName As String) As Boolean
    '    If GetTableAuth(tableName, authName) = False Then
    '        Return False
    '    End If

    '    Dim dat As New clsData
    '    Dim sql As New StringBuilder

    '    sql.Length = 0
    '    sql.AppendFormat("select ro.* ")
    '    sql.AppendFormat("from RoleOrganizationMapping View ro ")
    '    sql.AppendFormat("where 1=1 ")
    '    sql.AppendFormat("and ro.AuthName in ('{0}', 'Admin') ", authName)
    '    sql.AppendFormat("and ro.OrganizationID = {0} ", organizationID)
    '    sql.AppendFormat("and ro.RoleID in ({0}) ", GetRoleList())

    '    Return IIf(dat.GetData(sql.ToString(), Nothing, Data.CommandType.Text, "dt").Tables(0).Rows.Count = 0, False, True)
    'End Function

    'Public Shared Function GetAuth(ByVal organizationID As String, ByVal authName As String)
    '    Dim url As String = HttpContext.Current.Request.RawUrl.Split("/")(HttpContext.Current.Request.RawUrl.Split("/").Length - 1)

    '    Return GetAuth(url, organizationID, authName)
    'End Function

    '''' <summary>
    '''' 依表單和單位取得權限
    '''' </summary>
    '''' <param name="url"></param>
    '''' <param name="organizationID"></param>
    '''' <param name="authName"></param>
    '''' <returns></returns>
    '''' <remarks></remarks>
    'Public Shared Function GetAuth(ByVal url As String, ByVal organizationID As String, ByVal authName As String) As Boolean
    '    If GetProgramAuth(authName) = False Then
    '        Return False
    '    End If

    '    Dim dat As New clsData
    '    Dim sql As New StringBuilder

    '    sql.Length = 0
    '    'sql.AppendFormat("select ro.* ")
    '    'sql.AppendFormat("from FD_RoleOrganizationMapping View ro ")
    '    'sql.AppendFormat("where 1=1 ")
    '    'sql.AppendFormat("and ro.AuthName in ('{0}', 'Admin') ", authName)
    '    'sql.AppendFormat("and ro.OrganizationID = {0} ", organizationID)
    '    'sql.AppendFormat("and ro.RoleID in ({0}) ", GetRoleList())

    '    sql.AppendFormat("select oa.* ")
    '    sql.AppendFormat("from FD_UserOrganizationAuth oa ")
    '    sql.AppendFormat("where 1=1 ")
    '    sql.AppendFormat("and (oa.{0}Access = 'Y' or oa.AdminAccess = 'Y') ", authName)
    '    sql.AppendFormat("and oa.OrganizationID = {0} ", organizationID)
    '    sql.AppendFormat("and oa.UserID = '{0}' ", GetUserID())

    '    Return IIf(dat.GetData(sql).Rows.Count = 0, False, True)

    'End Function

    ''' <summary>
    ''' 取得目前登入者職務列表
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function GetRoleList() As String
        'Return Regex.Replace(HttpContext.Current.Request.Cookies("RoleList").Value, "(\d+)", "$1")
        Return Regex.Replace(clsCookie.CookieGet("RoleList"), "(\d+)", "$1")
    End Function

    ''' <summary>
    ''' 取得 user 職務列表
    ''' </summary>
    ''' <param name="userID"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function GetRoleList(ByVal userID As String) As String
        Dim dt As Data.DataTable
        Dim dat As New clsData
        Dim sql As New StringBuilder

        'sql.AppendFormat("select ru.* ")
        'sql.AppendFormat("from FD_RoleUserMappingView ru ")
        'sql.AppendFormat("where ru.UserID = '{0}' ", userID)
        sql.AppendFormat("select Value as RoleID ")
        sql.AppendFormat("from fn_GetAllPapasByUserID('{0}') ", userID)

        dt = dat.GetData(sql.ToString(), Nothing, Data.CommandType.Text, "dt").Tables(0)

        Dim roleList As New List(Of String)
        For Each dr As Data.DataRow In dt.Rows
            roleList.Add(dr("RoleID"))
        Next

        If roleList.Count = 0 Then
            roleList.Add("0")
        End If

        Return Regex.Replace(String.Join(",", roleList.ToArray()), "(\d+)", "'$1'")
    End Function

    Public Shared Function GetRoleIDByName(ByVal roleName As String) As String
        Dim dt As Data.DataTable
        Dim dat As New clsData
        Dim sql As New StringBuilder

        sql.AppendFormat("select r.* ")
        sql.AppendFormat("from Role r ")
        sql.AppendFormat("where r.RoleName = '{0}' ", roleName)

        dt = dat.GetData(sql.ToString(), Nothing, Data.CommandType.Text, "dt").Tables(0)

        Return dt.Rows(0)("RoleID")
    End Function

    '''' <summary>
    '''' 重新計算全部單位之樹狀代碼
    '''' </summary>
    '''' <remarks></remarks>
    Public Shared Sub BuildOrganizationCode()
        BuildOrganizationCode("null", "")
        BuildInternalCode("null", "")
    End Sub

    Private Shared Sub BuildOrganizationCode(ByVal parent As String, ByVal organizationCode As String)
        Dim dat As New clsData
        Dim sql As New StringBuilder

        sql.Length = 0

        'SQL2000 沒有 row_number() function, 改用 temp table
        sql.AppendFormat("create table #a (OrganizationID int, OrganizationCode int identity) ")
        sql.AppendFormat("insert #a (OrganizationID) ")
        sql.AppendFormat("select OrganizationID from Organization ")

        ' Root
        If parent = "null" Then
            sql.AppendFormat("where Parent is null ", parent)
        Else
            sql.AppendFormat("where Parent = {0} ", parent)
        End If

        sql.AppendFormat("order by OrganizationID ")

        sql.AppendFormat("update o set ")
        'sql.AppendFormat("OrganizationCode = '{0}' + case when Internal = 'Y' then '' else '0' end + char(o_code.OrganizationCode+48) ", organizationCode)
        sql.AppendFormat("OrganizationCode = '{0}' + right('0'+cast(o_code.OrganizationCode as nvarchar(10)), 2) ", organizationCode)
        sql.AppendFormat("from Organization o ")
        sql.AppendFormat("inner join ( ")
        'sql.AppendFormat("select OrganizationID ")
        'sql.AppendFormat(", row_number() over (order by OrganizationID) as OrganizationCode ")
        'sql.AppendFormat("from Organization ")

        sql.AppendFormat("select OrganizationID ")
        sql.AppendFormat(", OrganizationCode ")
        sql.AppendFormat("from #a) o_code on o.OrganizationID = o_code.OrganizationID ")

        '' Root
        'If parent = "null" Then
        '    sql.AppendFormat("where Parent is null) o_code on o.OrganizationID = o_code.OrganizationID ", parent)
        'Else
        '    sql.AppendFormat("where Parent = {0}) o_code on o.OrganizationID = o_code.OrganizationID ", parent)
        'End If

        'SQL2000 沒有 row_number() function, 改用 temp table
        sql.AppendFormat("drop table #a ")

        dat.AccData(sql.ToString, Nothing, Data.CommandType.Text)

        sql.Length = 0
        sql.AppendFormat("select o.* ")
        sql.AppendFormat("from Organization o ")
        sql.AppendFormat("where 1=1 ")
        'sql.AppendFormat("where o.Active = 'Y' ")

        ' Root
        If parent = "null" Then
            sql.AppendFormat("and o.Parent is null ")
        Else
            sql.AppendFormat("and o.Parent = {0} ", parent)
        End If

        Dim dt As Data.DataTable = dat.GetData(sql.ToString(), Nothing, Data.CommandType.Text, "dt").Tables(0)

        For Each dr As Data.DataRow In dt.Rows
            BuildOrganizationCode(dr("OrganizationID"), dr("OrganizationCode"))
        Next

    End Sub

    Private Shared Sub BuildInternalCode(ByVal parent As String, ByVal internalCode As String)
        Dim dat As New clsData
        Dim sql As New StringBuilder

        sql.Length = 0

        'SQL2000 沒有 row_number() function, 改用 temp table
        sql.AppendFormat("create table #a (OrganizationID int, InternalCode int identity) ")
        sql.AppendFormat("insert #a (OrganizationID) ")
        sql.AppendFormat("select OrganizationID from Organization ")

        ' Root
        If parent = "null" Then
            sql.AppendFormat("where Parent is null ", parent)
        Else
            sql.AppendFormat("where Parent = {0} ", parent)
        End If

        sql.AppendFormat("order by OrganizationID ")

        sql.AppendFormat("update o set ")
        'sql.AppendFormat("OrganizationCode = '{0}' + case when Internal = 'Y' then '' else '0' end + char(o_code.OrganizationCode+48) ", organizationCode)
        sql.AppendFormat("InternalCode = case when Internal = 'Y' then '{0}' else '{0}' + right('0'+cast(o_code.InternalCode as nvarchar(10)), 2) end ", internalCode)
        sql.AppendFormat("from Organization o ")
        sql.AppendFormat("inner join ( ")

        sql.AppendFormat("select OrganizationID ")
        sql.AppendFormat(", InternalCode ")
        sql.AppendFormat("from #a) o_code on o.OrganizationID = o_code.OrganizationID ")

        'SQL2000 沒有 row_number() function, 改用 temp table
        sql.AppendFormat("drop table #a ")

        dat.AccData(sql.ToString, Nothing, Data.CommandType.Text)

        sql.Length = 0
        sql.AppendFormat("select o.* ")
        sql.AppendFormat("from Organization o ")
        sql.AppendFormat("where 1=1 ")

        ' Root
        If parent = "null" Then
            sql.AppendFormat("and o.Parent is null ")
        Else
            sql.AppendFormat("and o.Parent = {0} ", parent)
        End If

        Dim dt As Data.DataTable = dat.GetData(sql.ToString(), Nothing, Data.CommandType.Text, "dt").Tables(0)

        For Each dr As Data.DataRow In dt.Rows
            BuildInternalCode(dr("OrganizationID"), dr("InternalCode"))
        Next

    End Sub

    Public Shared Sub BuildOrganizationInternalCode()

    End Sub

    ''' <summary>
    ''' 重新計算全部志工隊之樹狀代碼
    ''' </summary>
    ''' <remarks></remarks>
    Public Shared Sub BuildVOrganizationCode()
        BuildVOrganizationCode("null", "")
    End Sub

    Private Shared Sub BuildVOrganizationCode(ByVal parent As String, ByVal vorganizationCode As String)
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        sql.Length = 0

        'SQL2000 沒有 row_number() function, 改用 temp table
        sql.AppendFormat("create table #a (VOrganizationID int, VOrganizationCode int identity) ")
        sql.AppendFormat("insert #a (VOrganizationID) ")
        sql.AppendFormat("select VOrganizationID from VOrganization ")

        ' Root
        If parent = "null" Then
            sql.AppendFormat("where Parent is null ", parent)
        Else
            sql.AppendFormat("where Parent = {0} ", parent)
        End If

        sql.AppendFormat("update o set ")
        'sql.AppendFormat("VOrganizationCode = '{0}' + char(o_code.VOrganizationCode+48) ", vorganizationCode)
        sql.AppendFormat("VOrganizationCode = '{0}' + right('000'+cast(o_code.VOrganizationCode as nvarchar(10)), 4) ", vorganizationCode)
        sql.AppendFormat("from VOrganization o ")
        sql.AppendFormat("inner join ( ")
        sql.AppendFormat("select VOrganizationID ")
        sql.AppendFormat(", VOrganizationCode ")
        'sql.AppendFormat(", row_number() over (order by VOrganizationID) as VOrganizationCode ")
        'sql.AppendFormat("from VOrganization ")
        sql.AppendFormat("from #a) o_code on o.VOrganizationID = o_code.VOrganizationID ")

        '' Root
        'If parent = "null" Then
        '    sql.AppendFormat("where Parent is null) o_code on o.VOrganizationID = o_code.VOrganizationID ", parent)
        'Else
        '    sql.AppendFormat("where Parent = {0}) o_code on o.VOrganizationID = o_code.VOrganizationID ", parent)
        'End If

        'SQL2000 沒有 row_number() function, 改用 temp table
        sql.AppendFormat("drop table #a ")

        dat.AccData(sql)

        sql.Length = 0
        sql.AppendFormat("select o.* ")
        sql.AppendFormat("from VOrganization o ")
        sql.AppendFormat("where 1=1 ")
        'sql.AppendFormat("where o.Active = 'Y' ")

        ' Root
        If parent = "null" Then
            sql.AppendFormat("and o.Parent is null ")
        Else
            sql.AppendFormat("and o.Parent = {0} ", parent)
        End If

        Dim dt As Data.DataTable = dat.GetData(sql)

        For Each dr As Data.DataRow In dt.Rows
            If dr("organizationtype") = "P" Then
                BuildVOrganizationCode(dr("VOrganizationID"), dr("VOrganizationCode"))
            End If

        Next

    End Sub

    Public Shared Function EncryptPassword(ByVal password As String) As String
        Dim md5 As New MD5CryptoServiceProvider
        Dim data() As Byte = System.Text.Encoding.Unicode.GetBytes(password)

        Return Convert.ToBase64String(md5.ComputeHash(data))
    End Function

    'Public Shared Function DecryptPassword(ByVal password As String) As String
    '    Return EncryptPassword(password)
    'End Function

    Public Shared Function GetParentProgramID(ByVal programID As Integer) As Nullable(Of Integer)
        Dim dat As New clsData
        Dim sql As New StringBuilder
        Dim dt As Data.DataTable

        sql.AppendFormat("select p.* ")
        sql.AppendFormat("from Program p ")
        sql.AppendFormat("where p.ProgramID = {0} ", programID)

        dt = dat.GetData(sql)
        If dt.Rows.Count > 0 Then
            If TypeOf dt.Rows(0)("Parent") Is DBNull Then
                Return Nothing
            Else
                Return dt.Rows(0)("Parent")
            End If
        Else
            Return Nothing
        End If
    End Function

    Public Shared Function GetParentRoleID(ByVal roleID As Integer) As Integer
        Dim dat As New clsData
        Dim sql As New StringBuilder
        Dim dt As Data.DataTable

        sql.AppendFormat("select r.* ")
        sql.AppendFormat("from Role r ")
        sql.AppendFormat("where r.RoleID = {0} ", roleID)

        dt = dat.GetData(sql)

        If TypeOf dt.Rows(0)("Parent") Is DBNull Then
            Return dt.Rows(0)("RoleID")
        Else
            Return dt.Rows(0)("Parent")
        End If

    End Function
    Public Shared Function GetRoleID(ByVal UserID As String) As Integer
        Dim sql As New MyStringBuilder
        Dim dat As New clsData
        sql.Length = 0
        sql.AppendFormat("Select RoleID From RoleUserMapping ")
        sql.AppendFormat("Where UserID = '{0}' ", UserID)
        Return dat.GetData(sql).Rows(0)("RoleID")
    End Function
    'Public Shared Function GetOrganizationID(ByVal UserID As String) As String
    '    Dim dat As New clsData
    '    Dim sql As New StringBuilder
    '    Dim dt As Data.DataTable

    '    sql.AppendFormat("select OrganizationID ")
    '    sql.AppendFormat("from FD_Employee ")
    '    sql.AppendFormat("where EmployeeID = '{0}' ", UserID)

    '    dt = dat.GetData(sql)

    '    If dt.Rows.Count > 0 Then
    '        If dt.Rows(0)("OrganizationID") = 2 Then
    '            Return 15
    '        Else
    '            Return dt.Rows(0)("OrganizationID")
    '        End If
    '    Else
    '        Return "-1"
    '    End If

    'End Function


    '   Public Shared Function GetOrganizationName(ByVal UserID As String) As String
    '       Dim dat As New clsData
    '       Dim sql As New StringBuilder
    '       Dim dt As Data.DataTable

    '       sql.AppendFormat("select b.OrganizationName ")
    '       sql.AppendFormat("from FD_Employee a ")
    'sql.AppendFormat("left join Organization b on a.OrganizationID=b.OrganizationID ")
    '       sql.AppendFormat("where a.EmployeeID = '{0}' ", UserID)

    '       dt = dat.GetData(sql)

    '       If dt.Rows.Count > 0 Then
    '           Return dt.Rows(0)("OrganizationName")
    '       Else
    '           Return "-1"
    '       End If

    '   End Function

    '   Public Shared Function IsRoadPerson(ByVal OrganizationID As String) As Boolean
    '       Dim dat As New clsData
    '       Dim sql As New StringBuilder
    '       Dim dt As Data.DataTable

    '       sql.AppendFormat("select * from FD_OrganizationRoadMapping ")
    '       sql.AppendFormat("where OrganizationID = '{0}' ", OrganizationID)
    '       sql.AppendFormat("and Manage_Type = '{0}' ", "2")
    '       dt = dat.GetData(sql)

    '       If dt.Rows.Count > 0 Then
    '           Return True
    '       Else
    '           Return False
    '       End If

    '   End Function

    Public Shared Function IsAdministrator() As Boolean
        Dim roleList() As String = GetRoleList().Split(",")
        Dim systemRoleID As Integer = GetRoleIDByName("Admin")

        For Each Role As String In roleList
            If Role.Contains(systemRoleID) = True Then
                Return True
            End If
        Next

        Return False

    End Function

    Public Shared Sub BuildOrganizationAuth(ByVal userID As String)
        'Dim userID As String = HttpContext.Current.User.Identity.Name
        Dim dat As New clsData
        Dim sql As New StringBuilder

        sql.AppendFormat("exec BuildUserOrganizationAuth '{0}' ", userID)

        dat.AccData(sql)
    End Sub

    'Public Shared Sub BuildCustomOrganizationAuth(ByVal userID As String)
    '    Dim dat As New clsData
    '    Dim sql As New StringBuilder

    '    sql.AppendFormat("exec BuildCustomUserOrganizationAuth '{0}' ", userID)

    '    dat.AccData(sql)
    'End Sub

    'Public Shared Sub ClearOrganizationAuth()
    '    Dim userID As String = HttpContext.Current.User.Identity.Name
    '    Dim dat As New clsData
    '    Dim sql As New StringBuilder

    '    sql.AppendFormat("delete from FD_UserOrganizationAuth ")
    '    sql.AppendFormat("where UserID = '{0}' ", userID)

    '    dat.AccData(sql)

    '    'sql.AppendFormat("delete from CustomUserOrganizationAuth ")
    '    'sql.AppendFormat("where UserID = '{0}' ", userID)

    '    'dat.AccData(sql)
    'End Sub

    Public Shared Sub BuildProgramAuth(ByVal userID As String)
        Dim dat As New clsData
        Dim sql As New StringBuilder

        sql.AppendFormat("exec BuildUserProgramAuth '{0}' ", userID)

        dat.AccData(sql)
    End Sub

    'Public Shared Sub ClearProgramAuth()
    '    Dim userID As String = HttpContext.Current.User.Identity.Name
    '    Dim dat As New clsData
    '    Dim sql As New StringBuilder

    '    sql.AppendFormat("delete from FD_UserProgramAuth ")
    '    sql.AppendFormat("where UserID = '{0}' ", userID)

    '    dat.AccData(sql)
    'End Sub

    Public Shared Function GetProgramUrl() As String
        Return HttpContext.Current.Request.RawUrl.Split("/")(HttpContext.Current.Request.RawUrl.Split("/").Length - 1)
    End Function
    Public Shared Function GetProgramID(ByVal Url As String) As String
        Dim dat As New clsData
        Dim sql As New MyStringBuilder
        Dim dt As DataTable
        sql.Length = 0
        sql.AppendFormat("SELECT ProgramID FROM Program ")
        sql.AppendFormat("WHERE Url like '%{0}%' ", Url)
        dt = dat.GetData(sql)

        If dt.Rows.Count > 0 Then
            If TypeOf dt.Rows(0)("ProgramID") Is DBNull Then
                Return ""
            Else
                Return dt.Rows(0)("ProgramID").ToString()
            End If
        Else
            Return ""
        End If
    End Function
    Public Shared Function GetUserID() As String
        'Return Current.Session("UserID")
        Return HttpContext.Current.User.Identity.Name
    End Function

    Public Shared Function GetUser() As clsUser
        Return New clsUser
    End Function

    Public Shared Function GetDefaultUrl(Optional ByVal login As Boolean = False) As String
        Dim prefix As String = "~\WebForm\"
        Dim userType As My.UserType

        If login = True Then
            userType = New My.UserType(clsCookie.CookieGet("UserTypeValue"))
        Else
            userType = clsAuth.GetUser().UserType
        End If

        If userType = My.UserType.Employee Then
            Return prefix + "Main.aspx"
        Else
            Return "~/Public/Login.aspx"
        End If
        'ElseIf userType = My.UserType.Volunteer Then
        '    Return prefix + "MainForVolunteer.aspx"
        'ElseIf userType = My.UserType.Person Then
        '    Return prefix + "MainForPerson.aspx"
        'End If

    End Function

    Public Shared Function GetSSOUrl() As String
        Return MyObj.GetParameter("Login", "SSOUrl")
    End Function

    Public Shared Function GetProgramName() As String
        Return My.MyPage.GetPageName()
    End Function

    '''' <summary>
    '''' 依據角色繼承關係
    '''' 重整角色單位對應表、角色表單對應表
    '''' </summary>
    '''' <remarks></remarks>

    ''' <summary>
    ''' 依據角色繼承關係
    ''' 重整角色單位對應表、角色表單對應表
    ''' </summary>
    ''' <remarks></remarks>
    Public Shared Sub RebuildRoleOrganizationMapping()
        Dim dat As New clsData
        Dim sql As New StringBuilder

        sql.Length = 0
        sql.AppendFormat("select r.* ")
        sql.AppendFormat("from Role r ")
        sql.AppendFormat("where Parent is null and r.Active = 'Y' ")

        Dim dtRole As Data.DataTable = dat.GetData(sql)

        '
        Using scope As New Transactions.TransactionScope
            sql.Length = 0
            sql.AppendFormat("select ro.* into #RoleOrganizationMapping ")
            sql.AppendFormat("from RoleOrganizationMapping ro ")
            sql.AppendFormat("inner join Role r on ro.RoleID = r.RoleID ")
            sql.AppendFormat("where Parent is null and r.Active = 'Y' ")

            dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)

            For Each dr As Data.DataRow In dtRole.Rows
                ReBuildRoleOrganizationMapping_Process2(dr("RoleID"))
            Next

            sql.Length = 0
            sql.AppendFormat("truncate table ")
            sql.AppendFormat("RoleOrganizationMapping ")
            dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)

            sql.Length = 0
            sql.AppendFormat("insert RoleOrganizationMapping (RoleID, OrganizationID, VOrganizationID, AuthName) ")
            sql.AppendFormat("select distinct RoleID, OrganizationID, VOrganizationID, AuthName ")
            sql.AppendFormat("from #RoleOrganizationMapping ")

            dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)

            sql.Length = 0
            sql.AppendFormat("drop table ")
            sql.AppendFormat("#RoleOrganizationMapping ")

            dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)

            scope.Complete()
        End Using
    End Sub


    Private Shared Sub ReBuildRoleOrganizationMapping_Process2(ByVal parent As String)
        Dim dat As New clsData
        Dim sql As New StringBuilder

        sql.Length = 0
        sql.AppendFormat("insert #RoleOrganizationMapping (RoleID, OrganizationID, VOrganizationID, AuthName) select ")
        sql.AppendFormat(" ro_child.RoleID, ro_child.OrganizationID, ro_child.VOrganizationID, ro_child.AuthName ")
        sql.AppendFormat("from RoleOrganizationMapping ro_child ")
        sql.AppendFormat("inner join Role r_child on r_child.RoleID = ro_child.RoleID ")
        sql.AppendFormat("inner join #RoleOrganizationMapping ro_parent on ro_child.OrganizationID = ro_parent.OrganizationID and ro_child.VOrganizationID = ro_parent.VOrganizationID and ro_child.AuthName = ro_parent.AuthName ")
        sql.AppendFormat("where 1=1 ")
        sql.AppendFormat("and r_child.Parent = '{0}' ", parent)
        sql.AppendFormat("and ro_parent.RoleID = '{0}' ", parent)

        dat.AccData(sql)

        sql.Length = 0
        sql.AppendFormat("select r.* ")
        sql.AppendFormat("from Role r ")
        sql.AppendFormat("where Parent = {0} and r.Active = 'Y' ", parent)

        Dim dtRole As Data.DataTable = dat.GetData(sql)

        For Each dr As Data.DataRow In dtRole.Rows
            ReBuildRoleOrganizationMapping_Process2(dr("RoleID"))
        Next
    End Sub


    ''' <summary>
    ''' 依據角色繼承關係
    ''' 重整角色表單對應表
    ''' </summary>
    ''' <remarks></remarks>
    Public Shared Sub RebuildRoleProgramMapping()
        Dim dat As New clsData
        Dim sql As New StringBuilder

        sql.Length = 0
        sql.AppendFormat("select r.* ")
        sql.AppendFormat("from Role r ")
        sql.AppendFormat("where Parent is null and r.Active = 'Y' ")

        Dim dtRole As Data.DataTable = dat.GetData(sql)

        '
        Using scope As New Transactions.TransactionScope
            sql.Length = 0
            sql.AppendFormat("select rp.* into #RoleProgramMapping ")
            sql.AppendFormat("from RoleProgramMapping rp ")
            sql.AppendFormat("inner join Role r on rp.RoleID = r.RoleID ")
            sql.AppendFormat("where Parent is null and r.Active = 'Y' ")

            dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)

            For Each dr As Data.DataRow In dtRole.Rows
                ReBuildRoleProgramMapping_Process2(dr("RoleID"))
            Next

            sql.Length = 0
            sql.AppendFormat("truncate table ")
            sql.AppendFormat("RoleProgramMapping ")
            dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)

            sql.Length = 0
            sql.AppendFormat("insertRoleProgramMapping (RoleID, ProgramID, AuthName) ")
            sql.AppendFormat("select distinct RoleID, ProgramID, AuthName ")
            sql.AppendFormat("from #RoleProgramMapping ")

            dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)

            sql.Length = 0
            sql.AppendFormat("drop table ")
            sql.AppendFormat("#RoleProgramMapping ")

            dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)

            scope.Complete()
        End Using
    End Sub

    Private Shared Sub ReBuildRoleProgramMapping_Process2(ByVal parent As String)
        Dim dat As New clsData
        Dim sql As New StringBuilder

        sql.Length = 0
        sql.AppendFormat("insert #RoleProgramMapping (RoleID, ProgramID, AuthName) select ")
        sql.AppendFormat(" rp_child.RoleID, rp_child.ProgramID, rp_child.AuthName ")
        sql.AppendFormat("from RoleProgramMapping rp_child ")
        sql.AppendFormat("inner join Role r_child on r_child.RoleID = rp_child.RoleID ")
        sql.AppendFormat("inner join #RoleProgramMapping rp_parent on rp_child.ProgramID = rp_parent.ProgramID and rp_child.AuthName = rp_parent.AuthName ")
        sql.AppendFormat("where 1=1 ")
        sql.AppendFormat("and r_child.Parent = '{0}' ", parent)
        sql.AppendFormat("and rp_parent.RoleID = '{0}' ", parent)

        dat.AccData(sql)

        sql.Length = 0
        sql.AppendFormat("select r.* ")
        sql.AppendFormat("from Role r ")
        sql.AppendFormat("where Parent = {0} and r.Active = 'Y' ", parent)

        Dim dtRole As Data.DataTable = dat.GetData(sql)

        For Each dr As Data.DataRow In dtRole.Rows
            ReBuildRoleProgramMapping_Process2(dr("RoleID"))
        Next
    End Sub

    '''' <summary>
    '''' 依登入者權限列出鄉鎮市
    '''' </summary>
    '''' <returns></returns>
    '''' <remarks></remarks>
    'Public Shared Function GetTownData() As Data.DataTable
    '    Dim dat As New clsData
    '    Dim sql As New StringBuilder
    '    'Dim dt As Data.DataTable

    '    Dim user As clsUser = clsAuth.GetUser()

    '    If user.RegionType = My.RegionType.County Then
    '        sql.Length = 0
    '        sql.AppendFormat("select r_town.RegionID, r_town.RegionName ")
    '        sql.AppendFormat("from Region r_town ")
    '        sql.AppendFormat("inner join Region r_county on r_town.Parent = r_county.RegionID ")
    '        sql.AppendFormat("inner join [FD_user] u on r_county.RegionID = u.RegionID ")
    '        sql.AppendFormat("where u.UserID='{0}' ", clsAuth.GetUserID())

    '    ElseIf user.RegionType = My.RegionType.Town Then
    '        sql.Length = 0
    '        sql.AppendFormat("select r.RegionID, r.RegionName ")
    '        sql.AppendFormat("from Region r ")
    '        sql.AppendFormat("inner join [FD_user] u on r.RegionID = u.RegionID ")
    '        sql.AppendFormat("where u.UserID='{0}' ", clsAuth.GetUserID())

    '    ElseIf user.RegionType = My.RegionType.Village Then
    '        sql.Length = 0
    '        sql.AppendFormat("select r.RegionID, r.RegionName ")
    '        sql.AppendFormat("from Region r ")
    '        sql.AppendFormat("inner join Region r_child on r.RegionID = r_child.Parent ")
    '        sql.AppendFormat("inner join [FD_user] u on r_child.RegionID = u.RegionID ")
    '        sql.AppendFormat("where u.UserID='{0}' ", clsAuth.GetUserID())

    '    End If

    '    'dt = dat.GetData(sql)

    '    Return dat.GetData(sql)
    'End Function

    '''' <summary>
    '''' 依登入者列出村里資料
    '''' </summary>
    '''' <param name="townID"></param>
    '''' <returns></returns>
    '''' <remarks></remarks>
    'Public Shared Function GetVillageData(ByVal townID As String) As Data.DataTable
    '    Dim dat As New clsData
    '    Dim sql As New StringBuilder
    '    'Dim dt As Data.DataTable

    '    Dim user As clsUser = clsAuth.GetUser()

    '    If user.RegionType = My.RegionType.County Or user.RegionType = My.RegionType.Town Then
    '        sql.Length = 0
    '        sql.AppendFormat("select r.RegionID, r.RegionName ")
    '        sql.AppendFormat("from Region r ")
    '        sql.AppendFormat("where r.Parent = '{0}'", townID)
    '    ElseIf user.RegionType = My.RegionType.Village Then
    '        sql.Length = 0
    '        sql.AppendFormat("select r.RegionID, r.RegionName ")
    '        sql.AppendFormat("from Region r ")
    '        sql.AppendFormat("inner join [FD_User] u on r.RegionID = u.RegionID ")
    '        sql.AppendFormat("where u.UserID='{0}' ", clsAuth.GetUserID())
    '        sql.AppendFormat("and r.Parent = '{0}'", townID)
    '    End If

    '    Return dat.GetData(sql)
    'End Function

    ''判斷是否為環保局人員
    'Public Shared Function IsEnvirPerson(ByVal MyOrganizationID As String) As Boolean
    '    If MyOrganizationID = 2 Or MyOrganizationID = 15 Then
    '        Return True
    '    Else
    '        Return False
    '    End If
    'End Function
End Class

